package com.demo.book;

import com.demo.bookshelf.BookShelfService;
import com.demo.common.model.Book;
import com.demo.common.model.Bookshelf;
import com.demo.common.model.Student;
import com.demo.student.StudentInterceptor;
import com.demo.student.StudentService;
import com.demo.student.StudentValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;

import java.util.List;

@Before(BookInterceptor.class)
public class BookController extends Controller {

    @Inject
    BookService bookService;

    @Inject
    BookShelfService bookShelfService;

    public void index() {
        Kv cond=Kv.create();
        if(StrKit.notBlank(getPara("bookid"))){
            cond.set("a.bookid",getPara("bookid"));
        }
        if(StrKit.notBlank(getPara("bookcopyid"))){
            cond.set("a.bookcopyid",getPara("bookcopyid"));
        }
        if(StrKit.notBlank(getPara("bookname"))){
            cond.set("a.bookname",getPara("bookname"));
        }
        if(StrKit.notBlank(getPara("bookauthor"))){
            cond.set("a.bookauthor",getPara("bookauthor"));
        }
        if(StrKit.notBlank(getPara("bookshelfno"))){
            cond.set("b.bookshelfno",getPara("bookshelfno"));
        }
        setAttr("bookPage", bookService.paginate(getParaToInt(0, 1), 10,Kv.by("cond",cond)));
        render("book.html");
    }

    public void add() {
        List<Bookshelf> lists=bookShelfService.findAll();
        setAttr("bookshelfs",bookShelfService.findAll());
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(BookValidator.class)
    public void save() {
        getBean(Book.class).save();
        redirect("/book");
    }

    public void edit() {
        setAttr("bookshelfs",bookShelfService.findAll());
        setAttr("book", bookService.findById(getParaToInt()));
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(BookValidator.class)
    public void update() {
        getBean(Book.class).update();
        redirect("/book");
    }

    public void delete() {
        bookService.deleteById(getParaToInt());
        redirect("/book");
    }
}
